package com.ybl.store.common.util;

import com.alibaba.fastjson2.JSONObject;
import com.ybl.store.common.convention.errorcode.BaseErrorCode;
import com.ybl.store.common.convention.exception.ClientException;
import com.ybl.store.common.properties.WxProperties;
import lombok.RequiredArgsConstructor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;

import java.io.IOException;

public class WeChatUtil {

    /**
     * 获取 openid
     *
     * @param code code
     * @return openid
     */
    public static String getOpenid(String appId,String appSecret,String tokenUrl,String code) {
        String url = String.format(tokenUrl, appId, appSecret, code);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String body = response.body().string();
//                System.out.println(body);
//                String jsonString =restTemplate
                JSONObject jsonObject = JSONObject.parseObject(body);
                if (jsonObject.containsKey("openid")) {
                    return jsonObject.getString("openid");
                }
                else{

                    throw new ClientException(String.format("errcode: %s errmsg: %s",jsonObject.getString("errcode"),jsonObject.getString("errmsg")),BaseErrorCode.MP_OPENID_NULL_ERROR);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

            return null;
    }
}
